<!-- 项目付款合同申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="purchaseBill" required>
          <u--input v-model="model.purchaseBill" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="propose" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="applicant" required>
          <h-select-depart-input
            disabled
            v-model="model.applicant"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>

        <u-form-item label="物品用途" prop="purchaseUse" required>
          <u--textarea
						:confirm-type="null"
            :maxlength="500"
						count 
						v-model="model.purchaseUse" 
						placeholder="请输入物品用途"
					></u--textarea>
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea 
						v-model="model.remark"
						placeholder="请输入备注"
						:confirm-type="null"
						:maxlength="500"
						count
					></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">调出信息</view>
        <u-form-item label="调出团队" prop="exportTeamId" required>
          <h-select-team-input
            style="width: 100%"
            v-model="model.exportTeamId"
            objectField="model.exportTeamId"
            placeholder="请选择调出团队"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            :tdlx="3"
						:purchaseCannibalizeDetailList="formData"
            @detail="handleChangeExportTeamId"
          />
        </u-form-item>
        <u-form-item label="调出日期" prop="exportTime" required>
          <h-time-select
            mode="datetime"
            ref="exportTime"
            v-model="model.exportTime"
            placeholder="请选择调出日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						@change="onExportTimeChange"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="调出仓库" prop="exportWarehouse" required>
          <h-dropdown
            class="w-100"
            keyName="categoryName"
            placeholder="请选择调出仓库"
            :columns="exportWarehouseList"
            v-model="model.exportWarehouse"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
            dataKey="result"
						@change="handleExportWarehouseChange('exportWarehouse', null, $event)"
          />
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">物资明细</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="handleAddMaterial">新增</u-button>
        </view>
				<template>
					<FormInfo 
						v-for="(item, index) in formData"
						:key="index"
						:item="item"
						:index="index"
						@edit="handleEditForm"
						@remove="handleRemoveForm"
						@copy="handleCopyForm"
					/>
				</template>
        <view>
        	<u-popup 
						mode="bottom" 
						closeable 
						:closeOnClickOverlay="false" 
						:round="10" 
						:show="showFormModal" 
						@close="closeFormModal" 
						@open="openFormModal"
					>
        	  <MaterialForm 
							ref="dataForm" 
							:index="index" 
							:exportTeamId="model.exportTeamId"
							:exportTeamName="model.exportTeamId_dictText"
							:exportWarehouse="model.exportWarehouse"
							:storehouseName="model.exportWarehouse_dictText" 
							@submit="handleFormSubmit" 
							@close="showFormModal = false" 
						/>
        	</u-popup>
        </view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">调入信息</view>
        <u-form-item label="调入团队" prop="foldTeamId" required>
          <h-select-team-input
            style="width: 100%"
            v-model="model.foldTeamId"
            objectField="model.foldTeamId"
            placeholder="请选择调入团队"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            border="surround"
            :tdlx="3"
            @detail="handleChangeFoldTeamId"
          />
        </u-form-item>
        <u-form-item label="调入日期" prop="foldTime" required>
          <h-time-select
            mode="datetime"
            ref="foldTime"
            v-model="model.foldTime"
            placeholder="请选择调入日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						@change="onFoldTimeChange"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="调入仓库" prop="foldWarehouse" required>
          <h-dropdown
            class="w-100"
            keyName="categoryName"
            placeholder="请选择调入仓库"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            :columns="foldWarehouseList"
            v-model="model.foldWarehouse"
            dataKey="result"
          />
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.purchaseFile" :isIcon="false"></h-upload-file>
          <file-list v-if="model.purchaseFile" v-model="model.purchaseFile" :isDelete="true"></file-list>
        </view>
      </view>
			
			<view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
				<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>
		
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, edit, info, queryByDepartment } from '@/api/purchase/ErpPurchaseCannibalizeForm'
import { convertCurrency } from '@/utils/utils'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗

import {
  addInvoiceHandleRecordList,
  erpOmcProjectId,
  relationTaskList,
  erpFinanceProjectDepositBillqueryByEntity,
  querySupplierByIdserpOmcProjectId,
	queryByIdPurchaseCannibalizeAllList,
	checkErpPurchaseCannibalize //检查库存
} from '@/api/index'
import fileList from '@/pages/synergy/components/fileList.vue'
import MaterialForm from './components/MaterialForm.vue'
import FormInfo from './components/MaterialFormInfo.vue'
export default {
  name: 'ErpOmcPayContractManagerForm',
  components: {
    fileList,
    // PrincipalForm,
    // PrincipalFormInfo,
    MaterialForm,
    FormInfo,
    // TaskInfo,
		ProcessNodeConfiguration
  },
  data() {
    return {
			warehouse: null, // 调出仓库值
			isSubmit: false,
      exportTeamId: '',
			isExportTeam: true, // 调出团队
			isFoldTeam: true, // 调入团队
      flag: false,
      cust_lxr: '',
      backUpApplicant: '',
      backUpTeamId: '',
      isReset: false,
      resetKey: '',
      index: null,
      showFormModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      formData: [],
      api: {
        queryByDepartment,
      },
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        purchaseBill: '',
        proposer: '',
        applicant: '',
        createTime: '',
        // 基本信息 - 非公用
        purchaseUse: '',
        emark: '',
        exportTeamId: '',
        exportTime: '',
        exportWarehouse: '',
        foldTeamId: '',
        foldTime: '',
        foldWarehouse: '',
        // 附件
        purchaseFile: null,
      },
      rules: {
				purchaseBill: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				applicant: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
				
        purchaseUse: [{ required: true, message: '请选择物品用途!', trigger: ['change', 'blur'] }],
        foldTeamId: [{ required: true, message: '请选择调入团队!', trigger: ['change', 'blur'] }],
        foldTime: [{ required: true, message: '请选择调入日期!', trigger: ['change', 'blur'] }],
        foldWarehouse: [{ required: true, message: '请选择调入仓库!', trigger: ['change', 'blur'] }],
        exportTeamId: [{ required: true, message: '请选择调出团队!', trigger: ['change', 'blur'] }],
        exportTime: [{ required: true, message: '请选择调出日期!', trigger: ['change', 'blur'] }],
        exportWarehouse: [{ required: true, message: '请选择调出仓库!', trigger: ['change', 'blur'] }],
      },
			
			// 代码生成后需手动设置流程编码
			flowCode: 'onl_erp_purchase_cannibalize',
			formUrl: '/erp/purchase/recipients/modules/ErpPurchaseCannibalizeForm',
			formUrlMobile: '/pages/synergy/erpPurchaseCannibalizeList',
			processId: '1540224492159131650',
			beanName: 'erpPurchaseCannibalizeServiceImpl'
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
			this.getapplyAllList()
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initBuyerInfo()
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
		moveHandle: function() {},
    handleChangeFoldTeamId(val, num = 0) {
      let v = val.id
			if (this.isFoldTeam) {
				this.foldTeamIdChange(v, true)
			} else {
				this.foldTeamIdChange(v, num)
			}
			this.isFoldTeam = false
			
      
    },
		
		// 查看物资明细
		getapplyAllList () {
			var params ={
				column: 'createTime',
				order: 'desc',
				pageNo: 1,
				pageSize: 100,
				billId: this.id
			}
			queryByIdPurchaseCannibalizeAllList(params).then(res => {
				if(res.success){
					this.formData = res.result || []
				}
			})
		},
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    foldTeamIdChange(id, edit) {
      if (this.model.exportTeamId == id) {
        this.$u.toast('调入团队不能和调出团队相同')
        this.$set(this.model, 'foldTeamId', null)
        this.$set(this.model, 'foldWarehouse', undefined)
        return false
      }
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.foldWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'foldWarehouse', undefined)
          }
          const data = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.foldWarehouseList = [data]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    // 新增物资
    handleAddMaterial() {
      if (!this.model.exportTeamId || !this.model.exportWarehouse) {
        this.$u.toast('请先填写调出信息')
        return false
      }
      this.index = null
      this.showFormModal = true
    },
    async handleChangeExportTeamId(v, num = 0) {
			if (this.exportTeamId != this.model.exportTeamId) {
				this.formData = []
			}
			if (this.id) {
				this.exportTeamIdChange(v, true)
			}
			if (v.id != this.exportTeamId) {
			  this.exportTeamIdChange(v, num)
			}
      this.exportTeamId = this.model.exportTeamId
    },
		
		// 調入日期
		onFoldTimeChange (item) {
			if (!this.model.exportTime) {
				this.$u.toast('请先选择调出日期')
				this.$nextTick(() => {
					this.model.foldTime = null
				})
			}
			let isBefore = moment(this.model.foldTime).isBefore(this.model.exportTime)
			if (isBefore) {
				this.$u.toast('调入日期必须大于调出日期！')
				this.$nextTick(() => {
					this.model.foldTime = null
				})
			}
			
		},
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
		// 调出日期
		onExportTimeChange (item) {
			let isBefore = moment(this.model.foldTime).isBefore(this.model.exportTime)
			if (isBefore) {
				this.$nextTick(() => {
					this.model.foldTime = null
				})
			}
		},
		handleExportWarehouseChange(key, fn, data) {
			if (!!this.model.exportWarehouse && !!data) {
				// 判断采购大类是否变化
				if (this.warehouse !== data) {
					let details = this.formData
					if (details && details.length > 0) {
						const _this = this;
						uni.showModal({
							title: '是否确认',
							content: "是否确认切换仓库，此操作将会清空明细表中已填写的所有信息？",
							success: (res) => {
								if (res.confirm) {
									this.warehouse = this.model.exportWarehouse
									// 清空子表数据
									this.formData = []
								} else {
									this.model.exportWarehouse = this.warehouse
								}
							} 
						})
					} else {
						this.warehouse = data
					}
				}
			}
			
			this.exportWarehouseList.forEach(ex => {
				if (ex.id == data) {
					this.$set(this.model, 'exportWarehouse_dictText', ex.categoryName)
				}
			})
		},
    exportTeamIdChange(row, edit = false) {
      const id = row.id
      if (this.model.foldTeamId == id) {
        this.model.exportTeamId = this.exportTeamId
        this.$u.toast('调入团队不能和调出团队相同')
				this.$set(this.model, 'exportTeamId', null)
				this.$set(this.model, 'exportWarehouse', undefined)
				this.exportWarehouseList = []
        return false
      }
      // 清空子表
      // this.$refs.cannibalizeDetailList.reset()
      // this.warehouse = null
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.exportWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'exportWarehouse', undefined)
            this.warehouse = null
          } else {
						this.warehouse = this.model.exportWarehouse
					}
          const list = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.exportWarehouseList = [list]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
			this.showFormModal = false
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo()
      this.model.purchaseBill = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.purchaseBill //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.applicant = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
			this.exportTeamId = data.exportTeamId
			this.warehouse = data.exportWarehouse
    },
    resetProject() {},
    resetForm() {},
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (!this.formData.length) {
          this.$u.toast('请添加物资明细信息！')
          return Promise.reject('请添加物资明细信息！')
        }
        return Promise.resolve()
      })
    },
		
		// 检查库存
		checkErpPurchaseCannibalize() {
			let details = this.formData
			if(!!details&&details.length!=0){
				this.model.detailList = details
				return checkErpPurchaseCannibalize({...this.model, detailList: this.formData}).then(res => {
					if (res.success && !!res.result && res.result.isOk) {
						return Promise.resolve()
					} else if(!res.result.isOk){
						this.$u.toast("（调出团队） " + this.model.exportWarehouse_dictText + " 仓库 " + res.result.material_dictText + " "+ res.result.message)
						return Promise.reject("（调出团队） " + this.model.exportWarehouse_dictText + " 仓库 " + res.result.material_dictText + " "+ res.result.message)
					}
				})
			}else {
				this.$refs.form.validate()
				this.$emit('unButtonDisable');
			}
		},
    async onSubmit() {
      await this.validateForm()
			await this.checkErpPurchaseCannibalize()
			this.isSubmit = true
      try {
        this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
        const response = await url({
          ...this.model,
          detailList: this.formData,
        })
        this.$u.toast(response.message)
        if (response.success) {
        	var that = this
        	
        	// 获取流程列表
        	if (this.model.id) {
        		this.getProcessList(this.model.id)
        	} else {
        	// 判断添加的时候是否有返回id值
        		if (response.result) {
        			this.getProcessList(response.result)
        		}
        	
        	}
        	this.$refs.uToast.show({
        		message: response.message,
        		type: 'default',
        		complete () {
        			// that.isSubmit = false
        		}
        	})
        }
      } finally {
        // this.loading = false
      }
    },
    async onDraft() {
      // await this.validateForm()
			// await this.checkErpPurchaseCannibalize()
      this.isSubmit = true
      try {
        this.loading = true
      		var url = ''
      		if (this.id) {
      			url = edit
      		} else {
      			url = add
      		}
        const response = await url({
          ...this.model,
          detailList: this.formData,
        })
        if (response.success) {
    			
    			this.$refs.uToast.show({
    				message: response.message,
    				type: 'default',
    				complete () {
    					this.isSubmit = false
    					if (getCurrentPages().length > 1) {
    						uni.navigateBack()
    					} else {
    						uni.reLaunch({
    							url: '/pages/home/home'
    						})
    					}
    					
    				}
    			})
        }
      } finally {
        this.loading = false
      }
    },
		
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		}
  }
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
.showFormModal{ 
		overflow: hidden;
		position: fixed;
}
</style>
